//
//  ProcessPictureController.swift
//  QualityControlSystem
//
//  Created by Daniel Hu on 1/16/17.
//  Copyright © 2017 com.mask. All rights reserved.
//

import UIKit
import QBImagePickerController
import AssetsLibrary
import MWPhotoBrowser

enum Action {
    case add
    case edit
}

class ProcessPictureController: UICollectionViewController, UINavigationControllerDelegate {
    
    var status: ProcessStatus
    var projectId: String?
    var subProjectId: String?
    var processId: String?
    var data = [AnyObject]()
    var currentIdx: Int?
    var isShowHeaderText: Bool = false
    var action: Action?
    let bottomBtn = UIButton(type: .custom)
    let sectionInsets = UIEdgeInsets(top: Padding.top, left: Padding.left, bottom: Padding.top, right: Padding.left)
    let testText = "按实际的垃圾电视剧阿里的加拉涉及到垃圾死老弟就爱上的将来升级到了建安大螺丝就"
    
    init(collectionViewLayout: UICollectionViewFlowLayout, status: ProcessStatus, projectId: String?, subProjectId: String?, processId: String?) {
        self.status = status
        self.projectId = projectId
        self.subProjectId = subProjectId
        self.processId = processId
        super.init(collectionViewLayout: collectionViewLayout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = Color.bgGray
        
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints({ make in
            make.bottom.left.right.equalTo(view)
            make.height.equalTo(40)
        })
        
        if status == .pass || status == .review {
            collectionView?.register(ProcessImageCell.self, forCellWithReuseIdentifier: "reuse")
            collectionView?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "nilHeader")
        } else {
            collectionView?.register(ProcessImageCell.self, forCellWithReuseIdentifier: "reuse")
            collectionView?.register(ProcessPictureHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        }
        setupUI()
    }
    
    func setupUI() {
        if let role = User.shared.role {
            //要注释掉
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "历史照片", style: .plain, target: self, action: #selector(showHistoryPictures))
            bottomBtn.addTarget(self, action: #selector(bottomBtnPressed), for: .touchUpInside)
            switch role {
            case .worker, .monitor:
                bottomBtn.backgroundColor = UIColor.white
                bottomBtn.setTitle("提交质检报告", for: .normal)
                bottomBtn.setTitleColor(UIColor.black, for: .normal)
                break
            case .inspector:
                navigationItem.rightBarButtonItem = UIBarButtonItem(title: "历史照片", style: .plain, target: self, action: #selector(showHistoryPictures))
                let frame = (collectionView?.frame)!
                collectionView?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height - 40)
                bottomBtn.backgroundColor = UIColor.white
                bottomBtn.setTitle("提交质检报告", for: .normal)
                bottomBtn.setTitleColor(UIColor.black, for: .normal)
                break
            default:
                break
            }
        }
    }
    
    func bottomBtnPressed() {
        data.uploadAllPicturesWith(projectID: Int(projectId!)!, subProjectID: Int(subProjectId!)!, completion: { response in
            
        })
    }
    
    func showHistoryPictures() {
        let vc = HistoryPicListController(style: .plain, processId: processId)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: - UICollectionViewDataSource
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if status == .upload || status == .reform {
            return data.count + 1
        } else {
            return data.count
        }
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuse", for: indexPath) as! ProcessImageCell
        if data.count == 0 || (data.count == 0 && indexPath.row > data.count) {
            cell.imageView.image = UIImage(named: "add_picture")
        } else {
            if indexPath.row < data.count {
                let process = data[indexPath.row] as? SubProjectProcess
                cell.asset = process?.asset
            } else {
                cell.imageView.image = UIImage(named: "add_picture")
            }
        }
        return cell
    }
    
    // MARK: - UICollectionViewDelegate
    
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if status == .pass || status == .review {
            let nilHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "nilHeader", for: indexPath)
            return nilHeader
        } else {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as? ProcessPictureHeader
            header?.isShow = isShowHeaderText
            header?.headerText = testText
            header?.headerClickedBlock = { [weak self] (isShowText: Bool) in
                self?.isShowHeaderText = isShowText
                self?.collectionView?.reloadData()
            }
            return header!
        }
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        currentIdx = indexPath.row
        if data.count == 0 || indexPath.row == data.count {
            // select add button cell
            action = .add
            let addPicture = alertController()
            addPicture.addAction(photoLibary())
            addPicture.addAction(camera())
            addPicture.addAction(cancel())
            present(addPicture, animated: true, completion: nil)
        } else {
            action = .edit
            let imageOptions = alertController()
            imageOptions.addAction(originalImage())
            imageOptions.addAction(photoLibary())
            imageOptions.addAction(camera())
            imageOptions.addAction(delete())
            imageOptions.addAction(cancel())
            present(imageOptions, animated: true, completion: nil)
        }
    }
    
    // MARK: - Private
    
    func autoAdjustHeight() -> CGSize {
        let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 15.0)] as [String : Any]
        let labelSize = testText.boundingRect(with: CGSize(width: Screen.width - 2*Padding.left, height: 0), options: .usesLineFragmentOrigin, attributes:attributes, context: nil)
        if labelSize.size.height < 24 {
            return CGSize(width: Screen.width, height: 44.0)
        } else {
            return CGSize(width: Screen.width, height: labelSize.size.height + 20)
        }
    }
    
    func imageOptionsController() -> UIAlertController {
        let foo = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        return foo
    }
    
    func camera() -> UIAlertAction {
        let action = UIAlertAction(title: "相机", style: .default, handler: { action in
            let vc = UIImagePickerController()
            vc.sourceType = .camera
            vc.delegate = self
            self.present(vc, animated: true, completion: nil)
        })
        return action
    }
    
    func photoLibary() -> UIAlertAction{
        let action = UIAlertAction(title: "从相册选择", style: .default, handler: { action in
            let vc = QBImagePickerController()
            vc.delegate = self
            if self.action == .add {
                vc.allowsMultipleSelection = true
            } else {
                vc.allowsMultipleSelection = false
            }
            self.present(vc, animated: true, completion: nil)
        })
        return action
    }
    
    func cancel() -> UIAlertAction {
        let action = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        return action
    }
    
    func originalImage() -> UIAlertAction {
        let action = UIAlertAction(title: "查看原图", style: .default, handler: { action in
            let process = self.data[self.currentIdx!] as! SubProjectProcess
            var photos = [Any]()
            photos.append(MWPhoto(asset: process.asset, targetSize: CGSize(width: Screen.width, height: 200)))
            let photoBrowser = MWPhotoBrowser(photos: photos)
            self.navigationController?.pushViewController(photoBrowser!, animated: true)
        })
        return action
    }
    
    func delete() -> UIAlertAction {
        let action = UIAlertAction(title: "删除", style: .destructive, handler: { action in
            if let item = self.currentIdx {
                self.data.remove(at: item)
                let items = [IndexPath(item: item, section: 0)]
                self.collectionView?.deleteItems(at: items)
            }
        })
        return action
    }
    
    func alertController() -> UIAlertController {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        return alert
    }
}

extension ProcessPictureController: QBImagePickerControllerDelegate {
    
    func qb_imagePickerController(_ imagePickerController: QBImagePickerController!, didFinishPickingAssets assets: [Any]!) {
        if action == .add {
            let resultSize = data.count
            for asset in assets {
                let process = SubProjectProcess()
                process.asset = asset as? PHAsset
                data.append(process)
            }
            var indexs = [IndexPath]()
            let count = assets.count + resultSize
            for idx in resultSize..<count {
                indexs.append(IndexPath(item: idx, section: 0))
            }
            collectionView?.insertItems(at: indexs)
        } else {
            let process = data[currentIdx!] as! SubProjectProcess
            process.asset = assets.first as? PHAsset
            let index = IndexPath(row: currentIdx!, section: 0)
            let indexs = [index]
            collectionView?.reloadItems(at: indexs)
        }
        dismiss(animated: true, completion: nil)
    }
    
    func qb_imagePickerControllerDidCancel(_ imagePickerController: QBImagePickerController!) {
        dismiss(animated: true, completion: nil)
    }
}

extension ProcessPictureController: UIImagePickerControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //        let assets = asset
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}

extension ProcessPictureController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: Constant.itemWidth, height: Constant.itemHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return sectionInsets
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return sectionInsets.left
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if status == .pass || status == .review {
            return CGSize.init(width: 0.0, height: 0.0)
        } else {
            if isShowHeaderText == true {
                return autoAdjustHeight()
            } else {
                return CGSize.init(width: Screen.width, height: 44.0)
            }
        }
    }
}
